package com.lzx.iteam;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.*;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.*;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.lzx.iteam.bean.AddressData;
import com.lzx.iteam.bean.AttendanceData;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.LocationUtil;
import com.lzx.iteam.util.RongLoctionTool;
import com.lzx.iteam.util.StringUtil;
import io.rong.message.LocationMessage;

/**
 * Created by Megan on 16/4/7.
 */
public class BaiduMapActivity extends Activity implements OnGetPoiSearchResultListener, OnGetGeoCoderResultListener, BaiduMap.OnMapStatusChangeListener, View.OnClickListener {


    private String Tag = "BaiduMap";
    private MapView mMapView;
    private LinearLayout mLlBack, mLlSearch, mLlRoot;
    private TextView mOk;
    private AttendanceData attendanceData;
    private String mGroupName;
    private String mUserType;
    private String mContactId;

    BaiduMap mBaiduMap;
    private GeoCoder geoCoder;

    private MyLocationConfiguration.LocationMode mCurrentMode;
    private BitmapDescriptor mMarker;
    boolean isFirstLoc = true; // 是否首次定位
    private LocationUtil mLocationUtil;
    LocationMessage mChatLoction;
    private String address = "";
    private double longitude;
    private double latitude;

    private final int MAP_SEARCH = 100;
    private String mAction;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //在使用SDK各组件之前初始化context信息，传入ApplicationContext
        //注意该方法要再setContentView方法之前实现
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.baidu_map_layout);
        initViews();
        initMap();
        getIntentData();

    }

    private void initViews() {
        mMapView = (MapView) findViewById(R.id.mv_baidu_map);
        mLlBack = (LinearLayout) findViewById(R.id.ll_attendance_map_back);
        mOk = (TextView) findViewById(R.id.tv_attendance_map_ok);
        mLlRoot = (LinearLayout) findViewById(R.id.ll_baidu_map_root);
        mLlSearch = (LinearLayout) findViewById(R.id.ll_attendance_address_search);

        mLlBack.setOnClickListener(this);
        mOk.setOnClickListener(this);
        mLlSearch.setOnClickListener(this);
    }

    private void getIntentData() {
        Intent intent = getIntent();
        attendanceData = (AttendanceData) intent.getSerializableExtra("attendanceData");
        mGroupName = intent.getStringExtra("group_name");
        mUserType = intent.getStringExtra("user_type");
        mContactId = intent.getStringExtra("contact_id");

        mAction = intent.getAction();
        if ("attendance_update".equals(mAction)) {
            latitude = Double.parseDouble(attendanceData.getLatitude());
            longitude = Double.parseDouble(attendanceData.getLongitude());
            address = attendanceData.getAddress();
            LatLng latLng = new LatLng(latitude, longitude);
            MapStatus.Builder builder = new MapStatus.Builder();
            builder.target(latLng).zoom(18.0f);
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));

            geoCoder.reverseGeoCode(new ReverseGeoCodeOption()
                    .location(latLng));
        } else if ("CRM_update".equals(mAction)) {
            latitude = intent.getDoubleExtra("latitude", 0);
            longitude = intent.getDoubleExtra("longitude", 0);
            address = intent.getStringExtra("address");
            LatLng latLng = new LatLng(latitude, longitude);
            MapStatus.Builder builder = new MapStatus.Builder();
            builder.target(latLng).zoom(18.0f);
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));

            geoCoder.reverseGeoCode(new ReverseGeoCodeOption()
                    .location(latLng));
        } else if ("chat_loction".equals(mAction)) {
            ((TextView)findViewById(R.id.map_tv_title)).setText("地理位置");
            mChatLoction = intent.getParcelableExtra("location");
            if (mChatLoction != null) {
                mOk.setVisibility(View.GONE);
                findViewById(R.id.map_ll_search).setVisibility(View.GONE);
                latitude = mChatLoction.getLat();
                longitude = mChatLoction.getLng();
                LatLng latLng = new LatLng(latitude, longitude);
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(latLng).zoom(18.0f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));

                geoCoder.reverseGeoCode(new ReverseGeoCodeOption()
                        .location(latLng));
            }else{
                mOk.setText("发送位置");
            }
        }
    }

    private void initMap() {
        mBaiduMap = mMapView.getMap();
        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
        mBaiduMap
                .setMyLocationConfigeration(new MyLocationConfiguration(
                        mCurrentMode, true, null));
        //设置是否显示比例尺控件
        mMapView.showScaleControl(false);
        //设置是否显示缩放控件
        mMapView.showZoomControls(false);
        // 删除百度地图LoGo
        mMapView.removeViewAt(1);

        // 设置marker图标
        mMarker = BitmapDescriptorFactory.fromResource(R.drawable.marker_icon);
        //  mBaiduMap.setOnMapClickListener(this);//点击地图事件
        //  mBaiduMap.setOnMarkerClickListener(this);//点击覆盖物事件

        geoCoder = GeoCoder.newInstance();
        geoCoder.setOnGetGeoCodeResultListener(this);

        mBaiduMap.setOnMapStatusChangeListener(this);
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);

        mLocationUtil = new LocationUtil(this);
        mLocationUtil.setListener(new LocationUtil.LocationStatus() {
            @Override
            public void onLocated(BDLocation location) {
                // map view 销毁后不在处理新接收的位置
                if (location == null || mMapView == null) {
                    return;
                }

                Log.d(Tag, "当前位置经纬度：latitude=" + location.getLatitude() + ",longitude=" + location.getLongitude() + ",address" + location.getAddress() + ",addrStr" + location.getAddrStr());
                //  setMark(latitude, longitude, address);
                if ((!"attendance_update".equals(mAction)) && (!"CRM_update".equals(mAction))&&mChatLoction == null) {
                    latitude = location.getLatitude();
                    longitude = location.getLongitude();
                    address = location.getAddrStr();
                    showLocation(latitude, longitude, address);
                }
                MyLocationData locData = new MyLocationData.Builder()
                        .accuracy(location.getRadius())
                        // 此处设置开发者获取到的方向信息，顺时针0-360
                        .direction(100).latitude(location.getLatitude())
                        .longitude(location.getLongitude()).build();
                mBaiduMap.setMyLocationData(locData);
                if (isFirstLoc && (!"attendance_update".equals(mAction)) && (!"CRM_update".equals(mAction))&&mChatLoction == null) {
                    isFirstLoc = false;
                    LatLng ll = new LatLng(location.getLatitude(),
                            location.getLongitude());
                    MapStatus.Builder builder = new MapStatus.Builder();
                    builder.target(ll).zoom(18.0f);
                    mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                }
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        // 退出时销毁定位
        if (mLocationUtil != null) {
            mLocationUtil.stopLocation();
            mLocationUtil.destoryLocation();
            mLocationUtil = null;
        }

        mMapView.onDestroy();
        mMapView = null;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onGetPoiResult(PoiResult poiResult) {

    }

    @Override
    public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {

    }

    @Override
    public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_attendance_map_back:
                finish();
                break;
            case R.id.tv_attendance_map_ok:
                Log.d(Tag, "使用该地点：" + "address:" + address + ",latitude:" + latitude + ",longitude:" + longitude);

                if (StringUtil.isEmpty(address) || StringUtil.isEmpty(latitude + "") || StringUtil.isEmpty(longitude + "")) {
                    Toast.makeText(this, "地址为空，请重新选择", Toast.LENGTH_LONG).show();
                } else {
                    if ("CRM_update".equals(mAction) || "CRM_null".equals(mAction)) {
                        Intent intent = new Intent();
                        intent.putExtra("latitude", latitude);
                        intent.putExtra("longitude", longitude);
                        intent.putExtra("address", address);
                        setResult(RESULT_OK, intent);
                        finish();
                    }else if ((attendanceData != null && (!StringUtil.isEmpty(attendanceData.get_id()))) || "attendance_update".equals(mAction)) {
                        Intent intent = new Intent();
                        attendanceData.setAddress(address);
                        attendanceData.setLatitude(latitude + "");
                        attendanceData.setLongitude(longitude + "");
                        intent.putExtra("attendanceData", attendanceData);
                        setResult(RESULT_OK, intent);
                        finish();
                    } else if ("chat_loction".equals(mAction)) {
                        Uri uri = Uri.parse("http://api.map.baidu.com/staticimage?width=300&height=200&center=" + longitude + "," + latitude + "&zoom=17&markers=" + longitude + "," + latitude + "&markerStyles=m,A");
                        LocationMessage locationMessage = LocationMessage.obtain(latitude, longitude, address, uri);
                        //如果地图地位成功，那么调用
                        RongLoctionTool.mLastLocationCallback.onSuccess(locationMessage);
                        //如果地图地位失败，那么调用
                        RongLoctionTool.mLastLocationCallback.onFailure("定位失败!");
                        finish();

                    }  else {
                        Intent intent = new Intent(BaiduMapActivity.this, CloudDialerActivity.class);
                        attendanceData.setAddress(address);
                        attendanceData.setLatitude(latitude + "");
                        attendanceData.setLongitude(longitude + "");
                        intent.setAction("attendance_member_add");
                        intent.putExtra("attendanceData", attendanceData);
                        intent.putExtra("group_id", attendanceData.getGroupId());
                        intent.putExtra("tag_id", "0");
                        intent.putExtra("tag_name", mGroupName);
                        intent.putExtra("group_name", mGroupName);
                        intent.putExtra("user_type", mUserType);
                        intent.putExtra("contact_id", mContactId);
                        intent.putExtra("where", "cloud");
                        startActivity(intent);

                    }

                }
                break;
            case R.id.ll_attendance_address_search:
                float y = mLlSearch.getScrollY();
                int height = mLlSearch.getHeight();
                TranslateAnimation animation = new TranslateAnimation(0, 0, 0, -y);
                animation.setDuration(500);
                animation.setFillAfter(true);
                animation.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        Intent channle_intent = new Intent(BaiduMapActivity.this, BaiduMapSearchActivity.class);
                        startActivityForResult(channle_intent, MAP_SEARCH);
                    }
                });
                mLlRoot.startAnimation(animation);
                break;
        }
    }

    /*@Override
    public void onMapClick(LatLng latLng) {
//获取经纬度
        latitude = latLng.latitude;
        longitude = latLng.longitude;
        Log.d(Tag, "latitude=" + latitude + ",longitude=" + longitude);

        //实例化一个地理编码查询对象
        GeoCoder geoCoder = GeoCoder.newInstance();
        //设置反地理编码位置坐标
        ReverseGeoCodeOption op = new ReverseGeoCodeOption();
        op.location(latLng);
        //发起反地理编码请求(经纬度->地址信息)
        geoCoder.reverseGeoCode(op);
        geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {

            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult arg0) {
                //获取点击的坐标地址
                address = arg0.getAddress();
               // setMark(latitude, longitude, address);
                showLocation(latitude, longitude, address);
                Log.d(Tag, "address=" + address);
            }

            @Override
            public void onGetGeoCodeResult(GeoCodeResult arg0) {

            }
        });
    }

    @Override
    public boolean onMapPoiClick(MapPoi mapPoi) {
        final String name = mapPoi.getName();
        LatLng latLng = mapPoi.getPosition();
        latitude = latLng.latitude;
        longitude = latLng.longitude;

        //实例化一个地理编码查询对象
        GeoCoder geoCoder = GeoCoder.newInstance();
        //设置反地理编码位置坐标
        ReverseGeoCodeOption op = new ReverseGeoCodeOption();
        op.location(latLng);
        //发起反地理编码请求(经纬度->地址信息)
        geoCoder.reverseGeoCode(op);
        geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {

            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult arg0) {
                //获取点击的坐标地址
                address = arg0.getAddress() + "(" + name + ")";
               // setMark(latitude, longitude, address);
                showLocation(latitude, longitude, address);
                Log.d(Tag, "address=" + address);
            }

            @Override
            public void onGetGeoCodeResult(GeoCodeResult arg0) {

            }
        });

        return false;
    }

    @Override
    public boolean onMarkerClick(Marker marker) {//点击覆盖物
        showLocation(marker);
        return false;
    }

    private void showLocation(final Marker marker) {  //显示气泡
        // 创建InfoWindow展示的view

        LatLng pt = null;
        double latitude, longitude;
        latitude = marker.getPosition().latitude;
        longitude = marker.getPosition().longitude;

        View view = LayoutInflater.from(this).inflate(R.layout.map_address_pop_layout, null); //自定义气泡形状
        TextView textView = (TextView) view.findViewById(R.id.tv_map_address);
        pt = new LatLng(latitude + 0.0004, longitude + 0.00005);
        textView.setText(marker.getTitle());

        // 定义用于显示该InfoWindow的坐标点
        // 创建InfoWindow的点击事件监听者
        InfoWindow.OnInfoWindowClickListener listener = new InfoWindow.OnInfoWindowClickListener() {
            public void onInfoWindowClick() {
                mBaiduMap.hideInfoWindow();//影藏气泡

            }
        };
        // 创建InfoWindow
        InfoWindow mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromView(view), pt, -47, listener);
        mBaiduMap.showInfoWindow(mInfoWindow); //显示气泡

    }

    //覆盖物
    private void setMark(double latitude, double longitude, String title) {//显示覆盖物
        //先清除图层
        mBaiduMap.clear();
        // 定义Maker坐标点
        LatLng point = new LatLng(latitude, longitude);
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.target(point).zoom(18.0f);
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
        // 构建MarkerOption，用于在地图上添加Marker
        MarkerOptions options = new MarkerOptions().position(point)
                .icon(mMarker);
        // 在地图上添加Marker，并显示
        // mBaiduMap.addOverlay(options);
        Marker marker = (Marker) mBaiduMap.addOverlay(options);
        marker.setTitle(title);
        Bundle bundle = new Bundle();
        bundle.putSerializable("recore", "ddd");
        marker.setExtraInfo(bundle);
    }

    */


    private void showLocation(double latitude, double longitude, String address) {  //显示气泡
        // 创建InfoWindow展示的view

        LatLng pt = null;

        View view = LayoutInflater.from(this).inflate(R.layout.map_address_pop_layout, null); //自定义气泡形状
        TextView textView = (TextView) view.findViewById(R.id.tv_map_address);
        pt = new LatLng(latitude + 0.0004, longitude + 0.00005);
        textView.setText(address);

        // 定义用于显示该InfoWindow的坐标点
        // 创建InfoWindow的点击事件监听者
        InfoWindow.OnInfoWindowClickListener listener = new InfoWindow.OnInfoWindowClickListener() {
            public void onInfoWindowClick() {
                //  mBaiduMap.hideInfoWindow();//影藏气泡

            }
        };
        // 创建InfoWindow
        InfoWindow mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromView(view), pt, -47, listener);
        mBaiduMap.showInfoWindow(mInfoWindow); //显示气泡

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case MAP_SEARCH:
                    AddressData addressData = (AddressData) data.getSerializableExtra("address");
                    latitude = addressData.getLatitude();
                    longitude = addressData.getLongitude();
                    //实例化一个地理编码查询对象
                    LatLng latLng = new LatLng(latitude, longitude);
                    MapStatus.Builder builder = new MapStatus.Builder();
                    builder.target(latLng).zoom(18.0f);
                    mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                    //设置反地理编码位置坐标
                    //发起反地理编码请求(经纬度->地址信息)
                    geoCoder.reverseGeoCode(new ReverseGeoCodeOption()
                            .location(latLng));
                    break;
            }
        }
    }

    @Override
    public void onMapStatusChangeStart(MapStatus mapStatus) {
        mBaiduMap.hideInfoWindow();
    }

    @Override
    public void onMapStatusChange(MapStatus mapStatus) {

    }

    @Override
    public void onMapStatusChangeFinish(MapStatus mapStatus) {
        LatLng ptCenter = mBaiduMap.getMapStatus().target; //获取地图中心点坐标
        // 反Geo搜索
        latitude = ptCenter.latitude;
        longitude = ptCenter.longitude;
        showLocation(latitude, longitude, "更新地址..");
        geoCoder.reverseGeoCode(new ReverseGeoCodeOption()
                .location(ptCenter));
    }

    @Override
    public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
        //设置地图中心点坐标
        MapStatusUpdate status = MapStatusUpdateFactory.newLatLng(geoCodeResult.getLocation());
        mBaiduMap.animateMapStatus(status);
    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
        //获取点击的坐标地址
        //  address = reverseGeoCodeResult.getAddress() ;
        address = reverseGeoCodeResult.getAddressDetail().city + reverseGeoCodeResult.getAddressDetail().district + reverseGeoCodeResult.getAddressDetail().street + reverseGeoCodeResult.getAddressDetail().streetNumber;
        LatLng latLng = reverseGeoCodeResult.getLocation();
        latitude = latLng.latitude;
        longitude = latLng.longitude;
        // setMark(latitude, longitude, address);
        showLocation(latitude, longitude, address);
        Log.d(Tag, "address=" + address);
    }
}